#include "ClientListener.h"
#include "Util.h"

MessageCenter* ClientListener::messageCenter = NULL;
ClientListener::ClientListener(ClientInfo* info, MessageCenter* mCenter)
{
	cInfo = info;
	ClientListener::messageCenter = mCenter;
}

ClientListener::~ClientListener(void)
{
}
int ClientListener::listenMessage(SOCKET ClientSocket)
{	
	if (ClientSocket == INVALID_SOCKET)
	{				
		return 1;
	}	
	int iResult;
    int recvbuflen = DEFAULT_BUFLEN;   	
	
	while (1) {
		char recvbuf[DEFAULT_BUFLEN] = {0};
		// Receive until the peer shuts down the connection
		iResult = recv(ClientSocket, recvbuf, recvbuflen, 0);
		//if (iResult < 0) {
		//	//printf("recv failed: %d\n", WSAGetLastError());
		//	closesocket(ClientSocket);
		//	WSACleanup();
		//	//mess = "receive failed";
		//}
		//add to message queue
		enqueueMessage(recvbuf);
	}
	//MessageBoxA(0,"6","asdasdddd",0);
	// shutdown the connection since we're done
    iResult = shutdown(ClientSocket, SD_SEND);
    if (iResult == SOCKET_ERROR) {
        printf("shutdown failed with error: %d\n", WSAGetLastError());
        closesocket(ClientSocket);
        WSACleanup();
        return 1;
    }

    // cleanup
    closesocket(ClientSocket);
    WSACleanup();

	return 0;
}


int ClientListener::startSocketListener()
{
	
	SOCKET mSocket = cInfo->mSocket;
	struct addrinfo *result = cInfo->result;	
	if (mSocket == INVALID_SOCKET) {
		//printf("socket failed: %ld\n", WSAGetLastError());

		if (result != NULL) {
			freeaddrinfo(result);
		}		
		
		WSACleanup();
		//lastError = "can't create listen socket";
		
		return 1;
	}
	
	DWORD dwThreadId;
	if(CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)&listenMessage, (LPVOID) mSocket, 0, &dwThreadId) == NULL)
	{		

		return 0;
	}
	return 0;
}

void ClientListener::enqueueMessage(char *message)
{
	char temp[DEFAULT_BUFLEN] = {0};
	strcpy_s(temp, DEFAULT_BUFLEN,message);
	messageCenter->enqueueMessage(temp);
}